package com.jiawei.Interaction;

import com.alibaba.fastjson.JSON;
import com.jiawei.pojo.ParamConfig;
import com.jiawei.pojo.ResponseMsg;
import com.jiawei.service.SerialPortServiceImpl;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Map;

/**
 * @author : willian fu
 * @version : 1.0
 */
@Component
@ServerEndpoint(value = "/websocket")
public class WebSocketServer {

    private Session session;

    SerialPortServiceImpl portService;


    @OnOpen
    public void open(Session session) {
        this.portService = new SerialPortServiceImpl();
        this.session = session;
        WebSocketUtil.webSocketMap.put(session.getId(), this);
        System.out.println(session.getId()+"已连接");
    }

    @OnClose
    public void onClose(){
        WebSocketUtil.webSocketMap.remove(session.getId());
        portService.close();
        System.out.println("客户端-"+session.getId()+"-下线！");
    }

    @OnMessage
    public void onMessage(String msg, Session session) throws IOException {
        System.out.println("收到=> "+msg);
        WebSocketServer webSocketServer = WebSocketUtil.webSocketMap.get(session.getId());
        Map<String, Object> data = (Map<String, Object>) JSON.parse(msg);
        ResponseMsg result = null;
        switch (String.valueOf(data.get("header"))){
            case "open":
                result = portService.open(new ParamConfig(String.valueOf(data.get("port")),
                        Integer.parseInt(String.valueOf(data.get("baudRate"))),
                        Integer.parseInt(String.valueOf(data.get("checkoutBit"))),
                        Integer.parseInt(String.valueOf(data.get("dataBit"))),
                        Integer.parseInt(String.valueOf(data.get("stopBit")))),session.getId());
                break;
            case "send":
                result = portService.send(String.valueOf(data.get("message")));
                break;
            case "search":
                result = portService.search();
                break;
            case "close":
                result = portService.close();
                break;
        }

        String jsonResult = JSON.toJSONString(result);
        webSocketServer.sendMsg(jsonResult);
    }

    @OnError
    public void onError(Session session,Throwable error){
        System.out.println(session.getId()+"发生错误"+error.getMessage());
        error.printStackTrace();
    }

    public void sendMsg(String msg) throws IOException {
        this.session.getBasicRemote().sendText(msg);
    }

    public void sendMsg(ByteBuffer msg) throws IOException {
        this.session.getBasicRemote().sendBinary(msg);
    }

}
